// import { Button, Dropdown, Menu} from 'antd';
import { GetMenuTree } from '@/services/system/menu';
import {
  addRole,
  delRole,
  GetPermissionById,
  GetRoleByPage,
  saveMenus,
  updateRole,
} from '@/services/system/role';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
const Role: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['null']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); // 绑定权限的弹框
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值

  const [menuIds, setMenuIds] = useState<React.Key[]>([]); // 保存行值
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建角色'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [treeData, setTreeData] = useState([{ title: '菜单树', key: '0-0', children: [] }]); //保存菜单数据的数据
  const [form] = Form.useForm();
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '角色编码', //表头显示的名称
      dataIndex: 'code', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '名称', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '描述', //表头显示的名称
      search: false,
      dataIndex: 'description', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑角色');
            form.setFieldsValue({
              name: record.name,
              code: record.code,
              description: record.description,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            // setRowData(record);
            // actionRef.current.reload();
            // setDeleteVisit(true);

            Modal.confirm({
              title: '删除角色',
              content: '确定要删除角色吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delRole({ id: record.id });
                actionRef.current.reload();
              },
            });
            // actionRef.current.reload();
          }}
        >
          删除
        </a>,
        <a
          key="linkPermission"
          onClick={async () => {
            setModalVisit2(true); // 显示角色弹框
            setRowData(record);
            const result = await GetPermissionById({ id: record.id });
            setCheckedKeys(result.data);
            // setTreeData(result.data);
            // setDeleteVisit(true);
            // actionRef.current.reload();
          }}
        >
          绑定权限
        </a>,
      ],
    },
  ];
  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await GetMenuTree();
      setTreeData(result.data);
    })();
  }, []);
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建角色') {
      const result = await addRole(form.getFieldsValue());
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateRole(form.getFieldsValue());
    }
    setConfirmLoading(false);
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    // await addRole(form.getFieldsValue());
    setConfirmLoading2(true);
    await saveMenus({ roleId: rowData.id, menuIds: menuIds });
    // message.success('绑定关系');
    setConfirmLoading2(false);
    setModalVisit2(false);
    // 这个爆红不用管(从新加载页面)
    // actionRef.current.reload();
  };

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue: React.Key[], e: any) => {
    console.log('onCheck', checkedKeysValue);
    console.log('halfCheckedKeys====', e.halfCheckedKeys);
    setMenuIds([...checkedKeysValue, ...e.halfCheckedKeys]);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', selectedKeysValue);
    setSelectedKeys(selectedKeysValue);
    // actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="角色查询" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              // console.log(selectedRows, '---选取多行----');
              // 1.清空form
              setCreateOrUpdate(false);
              setFormTitle('新建角色');
              form.resetFields();
              //
              setModalVisit(true);
            }}
            type="primary"
          >
            新建角色
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const result = await GetRoleByPage(params);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={columns} //上面定义的
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>

          <Form.Item
            label="角色编码"
            name="code"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>

          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="描述"
            name="description"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={'添加角色和权限关系'}
        visible={modalVisit2}
        confirmLoading={confirmLoading2}
        onOk={handleSubmit2}
        onCancel={() => setModalVisit2(false)}
      >
        <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={treeData}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default Role;
